package com.miao.config;

import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.nio.conn.SchemeIOSessionStrategy;
import org.apache.http.protocol.HttpContext;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author <a href="https://gitee.com/a-tom-is-cry">Xing</a>
 * @Date 2025/9/16 23:09
 * @Description
 */
@Component
public class ResponseInterceptor implements RestClientBuilder.HttpClientConfigCallback {
    /**
     * Allows to customize the {@link CloseableHttpAsyncClient} being created and used by the {@link RestClient}.
     * Commonly used to customize the default {@link CredentialsProvider} for authentication
     * or the {@link SchemeIOSessionStrategy} for communication through ssl without losing any other useful default
     * value that the {@link RestClientBuilder} internally sets, like connection pooling.
     *
     * @param httpClientBuilder
     */
    @Override
    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
        HttpResponseInterceptor httpResponseInterceptor = new HttpResponseInterceptor() {
            /**
             * Processes a response.
             * On the server side, this step is performed before the response is
             * sent to the client. On the client side, this step is performed
             * on incoming messages before the message body is evaluated.
             *
             * @param response the response to postprocess
             * @param context  the context for the request
             * @throws HttpException in case of an HTTP protocol violation
             * @throws IOException   in case of an I/O error
             */
            @Override
            public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
                response.addHeader("X-Elastic-Product", "Elasticsearch");
            }
        };
        httpClientBuilder.addInterceptorFirst(httpResponseInterceptor);
        return httpClientBuilder;
    }
}

